/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

import dao.DAOAdded;
import dao.DAOProduct;
import dao.DAOProvider;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.swing.JOptionPane;
import java.util.Set;
import javax.swing.table.DefaultTableModel;
import plugin.DatePicker;
import pojo.*;

/**
 *
 * @author QTuan
 */
public class NhapHangKho extends javax.swing.JPanel {

    /**
     * Creates new form NhapHangKho
     */
    private DefaultTableModel model = new DefaultTableModel();
    private PersonnelDetail account= null;
    private String taikhoan = "";
    public NhapHangKho(PersonnelDetail account,String taikhoan) {
        initComponents();
        this.account = account;
        this.taikhoan = taikhoan;
        DAOProvider daoProvider = new DAOProvider();
        List<Provider> listProvider = daoProvider.getAllProvider();
        for(int i=0;i<listProvider.size();i++)
        {
            this.jComboBox1.addItem(listProvider.get(i).getName());
        }
        model.addColumn("Id");
        model.addColumn("Tên sản phẩm");
        model.addColumn("Số lượng tồn");
        model.addColumn("Giá");
        model.addColumn("Số lương tối đa");
        model.addColumn("Số lượng tối thiểu");
        model.addColumn("Số lượng nhập thêm");
        this.jTable1.setModel(model);
        this.jSpinner1.setValue(1);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jDialog1 = new javax.swing.JDialog();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jButton6 = new javax.swing.JButton();
        jSpinner1 = new javax.swing.JSpinner();

        javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
        jDialog1.getContentPane().setLayout(jDialog1Layout);
        jDialog1Layout.setHorizontalGroup(
            jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jDialog1Layout.setVerticalGroup(
            jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        jLabel1.setText("Ngày nhập");

        jTextField1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextField1MouseClicked(evt);
            }
        });
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
        });

        jLabel2.setText("Nhà cung cấp");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel3.setText("Danh sách các hàng nhập");

        jLabel5.setText("Quét mã hoặc nhập id sản phẩm");

        jButton2.setText("Thêm sản phẩm");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Xóa sản phẩm");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel6.setText("Ngày  tạo");

        jTextField3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextField3MouseClicked(evt);
            }
        });
        jTextField3.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField3KeyPressed(evt);
            }
        });

        jButton6.setText("Lưu phiếu");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jSpinner1.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(53, 53, 53)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel3)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel5)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(76, 76, 76)
                                .addComponent(jLabel4)))
                        .addGap(36, 36, 36)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(31, 31, 31)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 965, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton6)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton6))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(16, 16, 16)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(29, 29, 29)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        String idstr = this.jTextField2.getText();
        if(TryParseInt(idstr)!= null)
        {
            Integer id = Integer.parseInt(idstr);
            boolean flag = false;
            for(int i=0;i<model.getRowCount();i++)
            {
                int temp = (Integer)model.getValueAt(i, 0);
                if((Integer)model.getValueAt(i, 0) == id)
                {
                    flag = true;
                    break;
                }
            }
            if(flag)
            {
                JOptionPane.showMessageDialog(null, "Sản phẩm đã có trong danh sách nhập hàng","Lỗi trùng",JOptionPane.ERROR_MESSAGE);
            }else
            {
                DAOProduct daoProduct = new DAOProduct();
                Product product = daoProduct.getProductById(id);
                if(product==null)
                {
                    JOptionPane.showMessageDialog(null, "Sản phẩm bạn tìm không tồn tại xin nhập lại hoặc tạo mới sản phẩm","Lỗi không tìm thấy",JOptionPane.ERROR_MESSAGE);
                }else
                {
                    int soluongnhap = (Integer)this.jSpinner1.getValue();
                    if(soluongnhap + product.getProCount() > product.getProCountM() || product.getProCount() < product.getProCountN())
                    {
                        int max = product.getProCountM()-product.getProCount();
                        JOptionPane.showMessageDialog(null, " Không thể nhập vì lỗi quy định 1 của công ty",
                                "Lỗi quy định",JOptionPane.ERROR_MESSAGE);
                    }else
                    {
                        model.addRow(new Object[]{product.getId(),product.getProName(),product.getProCount(),product.getProPrice(),product.getProCountM(),product.getProCountN(),soluongnhap});
                    }
                }
            }
        }else
        {
            JOptionPane.showMessageDialog(null, "Bạn phải nhập id là số","Lỗi id",JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        if(model.getRowCount()==0)
        {
            JOptionPane.showMessageDialog(null, "Không thể lưu phiếu nếu không có sản phẩm nào","Lỗi thiếu sản phẩm nhập",JOptionPane.ERROR_MESSAGE);
        }else
        {
            if(this.jTextField1.getText().equals(""))
            {
                JOptionPane.showMessageDialog(null, "Hãy chọn ngày nhập hàng để tiếp tục!","Thiếu ngày nhập",JOptionPane.WARNING_MESSAGE);
            }else
            {
                Added add = new Added();
                SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
                Date dateNhap = null;
                Date dateTao = null;
                try {
 
                    dateNhap = formatter.parse(this.jTextField1.getText());
                    if(this.jTextField3.getText().equals(""))
                    {
                        dateTao = new Date();
                    }else
                    {
                        dateTao = formatter.parse(this.jTextField3.getText());
                    }
                    
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                add.setDtimeAdd(dateNhap);
                add.setDtimeCreate(dateTao);
                add.setIsBlock(0);
                add.setPerAccount(this.taikhoan);
                add.setProvider((String)this.jComboBox1.getSelectedItem());
                
                /*List<AddedProductId> dsSanPham = new ArrayList<AddedProductId>();
                for(int i=0;i<model.getRowCount();i++)
                {
                    AddedProductId temp = new AddedProductId();
                    temp.setIdAdded(i);
                }*/
                DAOProduct daoProduct = new DAOProduct();
                Set<Product> listProduct = new HashSet<Product>();
                for(int i=0;i<model.getRowCount();i++)
                {
                    Product temp = daoProduct.getProductById((Integer)model.getValueAt(i, 0));
                    temp.setProCount(temp.getProCount()+(Integer)this.jSpinner1.getValue());
                    listProduct.add(temp);
                }
                
                add.setProducts(listProduct);
                DAOAdded daoAdded = new DAOAdded();
                daoAdded.setAdded(add);
                JOptionPane.showMessageDialog(null, "Lưu hóa đơn thanh công","Lưu hóa đơn thanh công",JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        int[] select = this.jTable1.getSelectedRows();
        for(int i=0;i<select.length;i++)
        {
            model.removeRow(select[i]);
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jTextField1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextField1MouseClicked
        this.jTextField1.setText(new DatePicker(this).setPickedDate());
    }//GEN-LAST:event_jTextField1MouseClicked

    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed
        this.jTextField1.setText(new DatePicker(this).setPickedDate());
    }//GEN-LAST:event_jTextField1KeyPressed

    private void jTextField3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextField3MouseClicked
        this.jTextField3.setText(new DatePicker(this).setPickedDate());
    }//GEN-LAST:event_jTextField3MouseClicked

    private void jTextField3KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField3KeyPressed
        this.jTextField3.setText(new DatePicker(this).setPickedDate());
    }//GEN-LAST:event_jTextField3KeyPressed
    public static Integer TryParseInt(String someText) {
        try {
            return Integer.parseInt(someText);
        } catch (NumberFormatException ex) {
        return null;
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton6;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JDialog jDialog1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSpinner jSpinner1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration//GEN-END:variables
}
